package com.itfreer.gather.setting;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.LinearLayout;

import com.itfreer.arcgis.layer.LayerLoader;
import com.itfreer.arcgis.utils.MapUtils;
import com.itfreer.data.ConfigSynProgressListener;
import com.itfreer.data.ConfigSynService;
import com.itfreer.gather.R;
import com.itfreer.gis.datasyn.DataSynService;
import com.itfreer.gis.datasyn.DataSynProgressListener;
import com.itfreer.security.SecurityService;
import com.itfreer.security.UserChangeListener;
import com.itfreer.security.UserInfoEntity;
import com.itfreer.ui.activity.BaseActivity;
import com.itfreer.ui.base.TextView;
import com.itfreer.utils.collection.SerializableMap;
import com.itfreer.utils.common.AlertUtils;
import com.itfreer.utils.common.RequestPermissionsUtils;
import com.itfreer.utils.common.ToastUtils;

/**
 * 我的界面
 */
public class SettingActivity extends BaseActivity {

    private ProgressDialog dataSynDialog;
    private ProgressDialog configSynDialog;
    private DataSynHandler dataSynHandler;
    private ConfigSynHandler configSynHandler;
    private UserInfoEntity userEntity;

    private TextView userNameText;
    private TextView userInfoText;
    private TextView loginButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting_activity);

        dataSynDialog = new ProgressDialog(this);
        configSynDialog = new ProgressDialog(this);
        dataSynHandler = new DataSynHandler();
        configSynHandler = new ConfigSynHandler();

        // 返回
        TextView back =(TextView)findViewById(R.id.setting_back);
        back.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                finish();
            }
        });

        // 系统登录
        loginButton = (TextView)findViewById(R.id.setting_login);
        loginButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(loginButton.getText().equals("系统登录")){
                    goLoginPage();
                }else{
                    SecurityService.instance.logout();
                }
            }
        });

        // 修改密码
        LinearLayout password =(LinearLayout)findViewById(R.id.setting_password);
        password.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(userEntity==null){
                    ToastUtils.showShort(SettingActivity.this, "请先系统登录！");
                    return;
                }
                goPasswordPage();
            }
        });

        // 技术支持
//        LinearLayout support =(LinearLayout)findViewById(R.id.setting_support);
//        support.setOnClickListener(new View.OnClickListener() {
//            public void onClick(View v) {
//                goSupportPage();
//            }
//        });

        // 关于
        LinearLayout about =(LinearLayout)findViewById(R.id.setting_about);
        about.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                goAboutPage();
            }
        });

        // 网络设置
        LinearLayout netword =(LinearLayout)findViewById(R.id.setting_netword);
        netword.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                goNetworkPage();
            }
        });

        // 数据同步
        LinearLayout dataSyn = (LinearLayout) findViewById(R.id.dataSynLayout);
        dataSyn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(userEntity==null){
                    ToastUtils.showShort(SettingActivity.this, "请先系统登录！");
                    return;
                }

                AlertUtils.dialog(SettingActivity.this, "系统提示", "确认启动数据同步操作？",
                    new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dataSynRequestPermissions();
                        }
                    },
                    new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }
                );
            }
        });

        // 配置同步
        LinearLayout configSyn = (LinearLayout) findViewById(R.id.configSynLayout);
        configSyn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(userEntity==null){
                    ToastUtils.showShort(SettingActivity.this, "请先系统登录！");
                    return;
                }

                AlertUtils.dialog(SettingActivity.this, "系统提示", "确认启动配置同步操作？",
                    new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            configSyn();
                        }
                    },
                    new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    }
                );
            }
        });

        // 用户信息
        userNameText = (TextView) findViewById(R.id.setting_user_name);
        userInfoText = (TextView) findViewById(R.id.setting_user_info);

        // 设置用户信息
        SecurityService.instance.setUserChangeListener(new UserChangeListener() {
            @Override
            public void change(UserInfoEntity user) {
                userEntity = user;
                if(userEntity!=null){
                    setUserInfo();
                }else{
                    userNameText.setText("未登录");
                    userInfoText.setText("您好，请登录");
                    loginButton.setText("系统登录");
                }
            }
        });

        // 初始化用户登录
        userEntity = SecurityService.instance.getUser();
        if(userEntity == null){
            SecurityService.instance.init(this);
        }else{
            setUserInfo();
        }
    }

    /**
     * 设置用户信息
     */
    private void setUserInfo(){
        userNameText.setText(userEntity.getUserName());
        userInfoText.setText("欢迎使用");
        loginButton.setText("注销登录");
    }

    protected void goLoginPage() {
        // 新建一个Intent对象
        Intent intent = new Intent();
        // 将map数据添加到封装的myMap中
        final SerializableMap dataMap = new SerializableMap();
        dataMap.setMap(null);
        Bundle bundle = new Bundle();
        bundle.putSerializable("map", dataMap);
        intent.putExtras(bundle);
        // 指定intent要启动的类
        intent.setClass(SettingActivity.this, LoginActivity.class);
        // 启动一个新的Activity
        startActivity(intent);
    }

    protected void goAboutPage() {
        // 新建一个Intent对象
        Intent intent = new Intent();
        // 将map数据添加到封装的myMap中
        final SerializableMap dataMap = new SerializableMap();
        dataMap.setMap(null);
        Bundle bundle = new Bundle();
        bundle.putSerializable("map", dataMap);
        intent.putExtras(bundle);
        // 指定intent要启动的类
        intent.setClass(SettingActivity.this, AboutActivity.class);
        // 启动一个新的Activity
        startActivity(intent);
    }

    protected void goNetworkPage() {
        // 新建一个Intent对象
        Intent intent = new Intent();
        // 将map数据添加到封装的myMap中
        final SerializableMap dataMap = new SerializableMap();
        dataMap.setMap(null);
        Bundle bundle = new Bundle();
        bundle.putSerializable("map", dataMap);
        intent.putExtras(bundle);
        // 指定intent要启动的类
        intent.setClass(SettingActivity.this, NetworkActivity.class);
        // 启动一个新的Activity
        startActivity(intent);
    }

    protected void goPasswordPage() {
        // 新建一个Intent对象
        Intent intent = new Intent();
        // 将map数据添加到封装的myMap中
        final SerializableMap dataMap = new SerializableMap();
        dataMap.setMap(null);
        Bundle bundle = new Bundle();
        bundle.putSerializable("map", dataMap);
        intent.putExtras(bundle);
        // 指定intent要启动的类
        intent.setClass(SettingActivity.this, PasswordActivity.class);
        // 启动一个新的Activity
        startActivity(intent);
    }

    /**
     * 到基础地图
     * @param v
     */
    public void goBaseMapPage(View v) {
        // 新建一个Intent对象
        Intent intent = new Intent();
        // 将map数据添加到封装的myMap中
        final SerializableMap dataMap = new SerializableMap();
        dataMap.setMap(null);
        Bundle bundle = new Bundle();
        bundle.putSerializable("map", dataMap);
        intent.putExtras(bundle);
        // 指定intent要启动的类
        intent.setClass(SettingActivity.this, BaseMapActivity.class);
        // 启动一个新的Activity
        startActivity(intent);
    }

    protected void goSupportPage() {
        // 新建一个Intent对象
        Intent intent = new Intent();
        // 将map数据添加到封装的myMap中
        final SerializableMap dataMap = new SerializableMap();
        dataMap.setMap(null);
        Bundle bundle = new Bundle();
        bundle.putSerializable("map", dataMap);
        intent.putExtras(bundle);
        // 指定intent要启动的类
        intent.setClass(SettingActivity.this, SupportActivity.class);
        // 启动一个新的Activity
        startActivity(intent);
    }

    // android 23 需要实时校验权限
    private void dataSynRequestPermissions() {
        if (ContextCompat.checkSelfPermission(SettingActivity.this,
                RequestPermissionsUtils.reqPermission[1]) == PackageManager.PERMISSION_GRANTED) {
            dataSyn();
        } else {
            ActivityCompat.requestPermissions(SettingActivity.this, RequestPermissionsUtils.reqPermission, RequestPermissionsUtils.WRITE_EXTERNAL_STORAGE);
        }
    }

    /**
     * 询问是否允许访问本地文件权限回调
     */
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == RequestPermissionsUtils.WRITE_EXTERNAL_STORAGE){
            dataSyn();
        }
    }

    private void dataSyn(){
        showDataSynDialog();
        DataSynService.instance.synData(new DataSynProgressListener(){

            @Override
            public void onSize(int count, int size, String s) {
                Message msg = new Message();
                Bundle b = new Bundle();
                b.putString("message", s);
                b.putInt("progress", size);
                b.putInt("count", count);
                msg.setData(b);
                dataSynHandler.sendMessage(msg);
                if(count==size){
                    LayerLoader.instance.setMapIsLoad(false);
                }
            }

            @Override
            public void onFail(String info) {
                Message msg = new Message();
                Bundle b = new Bundle();
                b.putString("message", info);
                msg.setData(b);
                dataSynHandler.sendMessage(msg);
            }
        });
    }

    private void configSyn(){
        showConfigSynDialog();
        ConfigSynService.instance.synConfig(new ConfigSynProgressListener(){

            @Override
            public void onSize(int count, int size, String s) {
                Message msg = new Message();
                Bundle b = new Bundle();
                b.putString("message", s);
                b.putInt("progress", size);
                msg.setData(b);
                configSynHandler.sendMessage(msg);
            }

            @Override
            public void onFail(String info) {
                Message msg = new Message();
                Bundle b = new Bundle();
                b.putString("message", info);
                msg.setData(b);
                configSynHandler.sendMessage(msg);
            }
        });
    }

    /**
     * 启动数据同步进度对话框
     */
    private void showDataSynDialog(){
        // 设置对话框参数
        dataSynDialog.setTitle("数据同步");
        dataSynDialog.setMessage("启动数据同步");
        dataSynDialog.setCancelable(false);
        // 设置进度条参数
        dataSynDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dataSynDialog.setMax(9);
        dataSynDialog.setProgress(0);
        dataSynDialog.setIndeterminate(false); // 填false表示是明确显示进度的 填true表示不是明确显示进度的
        dataSynDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        dataSynDialog.show();
    }

    /**
     * 启动数据同步进度对话框
     */
    private void showConfigSynDialog(){
        // 设置对话框参数
        configSynDialog.setTitle("配置同步");
        configSynDialog.setMessage("启动配置同步");
        configSynDialog.setCancelable(false);
        // 设置进度条参数
        configSynDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        configSynDialog.setMax(6);
        configSynDialog.setProgress(0);
        configSynDialog.setIndeterminate(false); // 填false表示是明确显示进度的 填true表示不是明确显示进度的
        configSynDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        configSynDialog.show();
    }

    private class DataSynHandler extends Handler {
        public DataSynHandler() {
        }

        // 子类必须重写此方法，接受数据
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // 此处可以更新UI
            Bundle b = msg.getData();
            String s = b.getString("message");
            int size = b.getInt("progress");
            int count = b.getInt("count");
            dataSynDialog.setMessage(s);
            dataSynDialog.setProgress(size);
            dataSynDialog.setMax(count);
        }
    }

    private class ConfigSynHandler extends Handler {
        public ConfigSynHandler() {
        }

        // 子类必须重写此方法，接受数据
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // 此处可以更新UI
            Bundle b = msg.getData();
            String s = b.getString("message");
            int size = b.getInt("progress");
            configSynDialog.setMessage(s);
            if(size!=0){
                configSynDialog.setProgress(size);
            }
        }
    }

    /**
     * 线测量
     */
    public void lineCL(View v) {
        setResult(10, null);
        finish();
    }

    /**
     * 面测量
     */
    public void polygonCL(View v) {
        setResult(20, null);
        finish();
    }
}
